/**
 * 封装图片上传功能
 * @type type
 */
$.extend({
    "imgUpload": function (callback) {
        var $input = $('<input type="file" id="file_input"  accept="image/*" />');
        $input.trigger('click');

        $input.on('change', function () {
            var file = this.files[0];
            //压缩图片
            $.compressImg(file, function (file) {
                //提交压缩过的图片
                $.ajaxImg(file, callback);
            });
        });
    },
    /**
     * 压缩图片
     * @param {type} file
     * @param {type} callback
     * @param {type} maxSize
     * @returns {Boolean}
     */
    "compressImg": function (file, callback, maxSize) {
        /**
         * 默认长宽不能超过3000px
         */
        if (!maxSize) {
            maxSize = 3000;
        }

        var type = file.type;

        if (!/image\/\w+/.test(type)) {
            $.toast("仅支持图片类型文件");
            return false;
        }

        var url = window.URL || window.webkitURL;
        var img = new Image();
        img.src = url.createObjectURL(file);

        /**
         * 通过加载url获取图片size
         * @returns {undefined}
         */
        img.onload = function () {
            var height = this.height;
            var width = this.width;
            var size = file.size;
            var maxSize = 3;
            var maxByte = maxSize * 1024 * 1024;
            var maxWH = 3000;


            /**
             * gif 不参与压缩
             */
            if (type.indexOf('gif') !== -1) {
                if (size >= maxByte) {
                    $.toast('图像不能大于' + maxSize + 'M');
                    return false;
                }
                callback(file);
                return true;
            }

            /**
             * 如果没有超过尺寸，也不进行压缩
             */
            if (height < maxWH && width < maxWH) {
                if (size >= maxByte) {
                    $.toast('图像不能大于' + maxSize + 'M');
                    return false;
                }
                callback(file);
                return true;
            }

            /**
             * 获取等比例压缩后的图片长宽
             */
            var newH, newW;
            if (height > width) {
                newH = maxWH;
                newW = newH * width / height;
            } else {
                newW = maxWH;
                newH = newW * height / width;
            }
            width = newW;
            height = newH;

            /**
             * 生成canvas
             */
            var canvas = document.createElement('canvas');
            var ctx = canvas.getContext('2d');
            canvas.width = width;
            canvas.height = height;

            /**
             * 填充白色背景，防止透明背景变黑色
             * 写入图片
             */
            ctx.fillStyle = "#fff";
            ctx.fillRect(0, 0, canvas.width, canvas.height);
            ctx.drawImage(this, 0, 0, canvas.width, canvas.height);

            /**
             * 到处二进制图片
             */
            var quality = 0.7;
            var base64 = canvas.toDataURL('image/jpeg', quality);
            var blob = $.base64Img2Blob(base64);
            callback(blob);
        };

    },
    "ajaxImg": function (file, callback) {
        var formData = new FormData();
        formData.append('file', file);
        var loadingIndex;
        $.ajax({
            "type": 'post',
            "timeout": 80000,
            "url": $.domain + '/Console/Image/doUpload',
            "data": formData,
            "cache": false,
            "processData": false,
            "contentType": false,
            "async": true,
            "beforeSend": function () {
                loadingIndex = $.loading("图片上传中");
            },
            "complete": function () {
                loadingIndex.close();
            }
        }).error(function () {
            $.toast('网络不给力');
        }).success(function (res) {
            callback(res);
        });
    },
    /**
     * 将base64图片转为2进制
     * @param {type} code
     * @returns {undefined}
     */
    "base64Img2Blob": function (code) {
        var parts = code.split(';base64,');
        var contentType = parts[0].split(':')[1];
        var raw = window.atob(parts[1]);
        var rawLength = raw.length;

        var uInt8Array = new Uint8Array(rawLength);

        for (var i = 0; i < rawLength; ++i) {
            uInt8Array[i] = raw.charCodeAt(i);
        }

        return new Blob([uInt8Array], {type: contentType});
    }
});


